package common

import (
	"encoding/json"
	"fmt"
	"sync"
	"time"

	"github.com/go-redis/redis"
)

var (
	redisOnce   sync.Once
	redisClient *redis.Client
)

type Redis struct {
	Conf *Config
}

func (s *Redis) Get() *redis.Client {
	redisOnce.Do(func() {
		redisClient = redis.NewClient(&redis.Options{
			Addr:     fmt.Sprintf("%s:%d", s.Conf.Get().Redis.Host, s.Conf.Get().Redis.Port),
			Password: s.Conf.Get().Redis.Password,
			DB:       s.Conf.Get().Redis.Db,
		})
		err := redisClient.Ping().Err()
		if err != nil {
			panic(err)
		}
	})
	return redisClient
}

func (s *Redis) Publish(name string, data interface{}) (err error) {
	body, e := json.Marshal(data)
	if e != nil {
		err = e
		return
	}
	client := s.Get()
	err = client.LPush(name, body).Err()
	return
}

func (s *Redis) Consume(name string, cb func(bs []byte)) (err error) {
	client := s.Get()
	for {
		data, err := client.BRPop(time.Second*3, name).Result()
		if err != nil {
			continue
		}
		cb([]byte(data[1]))
	}
}
